<?php
namespace app\common\model;
use think\Model;
use Qiniu\Auth as Auth;
use Qiniu\Config;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Qiniu\Processing\PersistentFop;
require_once APP_PATH . '/../vendor/qiniu/autoload.php';
class Qiniu extends Model
{
    public function remove ($path) {
       /*  $accessKey = getenv('QINIU_ACCESS_KEY');
        $secretKey = getenv('QINIU_SECRET_KEY');
        $bucket = getenv('QINIU_TEST_BUCKET'); */
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $auth = new Auth($accessKey, $secretKey);
        $auth = new Auth($accessKey, $secretKey);
        $config = new \Qiniu\Config();
        $bucketManager = new \Qiniu\Storage\BucketManager($auth, $config);
        $err = $bucketManager->delete($bucket, $path);
    }

    public function upload ($name=false,$ext=false) {
        $file = request()->file('file');
        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        if(!$ext) {
            $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        }
        if(!$ext) {
            $ext = 'png';
        }
        $allow = [
            'png','jpg','jpeg','gif','mp3','mp4','wav','mov','3gp','4gp','avi','rmvb','flv','m4a'
        ];
        if(!in_array($ext,$allow)) {
            return false;
        }
        // 上传到七牛后保存的文件名
        if($name) {
            $key = str_replace('.','',$_SERVER['SERVER_NAME'])."/{$name}/".date('Ymd')."/".date('His').rand(0, 9999).'.'.$ext;
        }else{
            $key = str_replace('.','',$_SERVER['SERVER_NAME'])."/".date('Ymd')."/".date('His').rand(0, 9999).'.'.$ext;
        }
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return false;
        } else {
            return $ret;
        }
    }

    /* 本地图片上传到远程服务器 */
    public function local2remote ($local,$name=false,$delete=true) {
        if(!file_exists($local)) {
            return false;
        }
        $filePath = $local;
        $ext = pathinfo($local, PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        if($name) {
            $key = str_replace('.','',$_SERVER['SERVER_NAME'])."/{$name}/".date('Ymd')."/".date('His').rand(0, 9999).'.'.$ext;
        }else{
            $key = str_replace('.','',$_SERVER['SERVER_NAME'])."/".date('Ymd')."/".date('His').rand(0, 9999).'.'.$ext;
        }
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if($delete) {
            unlink($local);
        }
        if ($err !== null) {
            return false;
        } else {
            return $ret;
        }
    }

    /* amr转换为mp3 */
    public function amr2mp3 ($key,$name) {
        $accessKey = config('qiniu_access');
        $secretKey = config('qiniu_secret');
        $auth = new Auth($accessKey, $secretKey);
        $bucket = config('qiniu_bucket');
        $domain = config('qiniu_domain');
        $token = $auth->uploadToken($bucket);
        $pipeline = 'amr2mp3';
        $force = false;
        //转码完成后通知到你的业务服务器。
        //$notifyUrl = request()->domain().'/amr';
        $notifyUrl = 'http://shop.xixi05.cn/api/notify/amr/mall_id/1';

        $config = new \Qiniu\Config();
        //$config->useHTTPS=true;
        $pfop = new PersistentFop($auth, $config);
        //要进行转码的转码操作。 http://developer.qiniu.com/docs/v6/api/reference/fop/av/avthumb.html
        $fops = "avthumb/mp3|saveas/" . \Qiniu\base64_urlSafeEncode($bucket . ":".$name);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, $notifyUrl, $force);
        //echo "\n====> pfop avthumb result: \n";
        if ($err != null) {
            //var_dump($err);
        } else {
            //echo "PersistentFop Id: $id\n";
        }
        //查询转码的进度和状态
        list($ret, $err) = $pfop->status($id);
       // echo "\n====> pfop avthumb status: \n";
        if ($err != null) {
           // var_dump($err);
        } else {
           // var_dump($ret);
        }
    }

    /* 水印 */
    public static function buildWaterMark ($url,$arr,$uid) {
        $userInfo = User::getOneById($uid);
        $url = tomedia($url);
        $url .= '?watermark/3';
        foreach($arr['list'] as $v) {
            if($v['type']=='nickname') {
                $v['type'] = 'text';
                $v['content'] = $userInfo['nickname'];
            }elseif($v['type']=='head') {
                $v['type'] = 'img';
                $v['content'] = $userInfo['headimgurl'];
            }elseif($v['type']=='qrcode') {
                $v['type'] = 'img';
                $href = request()->domain().'/m/chat/pages/index/index?refer_id='.$uid.'&mall_id='.$userInfo['mall_id'];
                $href = str_replace('&','%26',$href);
                $v['content'] = 'http://shop.xixi05.cn/qrcode?text='.$href;
            }
            if($v['type']=='text') {
                $v['fontSize'] *= 20;
                $url .= '/text/'.self::qiniubase64url($v['content']);
                $url .= "/gravity/NorthWest";
                $url .= "/dy/{$v['top']}";
                $url .= "/dx/{$v['left']}";
                $url .= "/fontsize/{$v['fontSize']}";
                $url .= "/fill/".self::qiniubase64url($v['color']);
            }else{
                $width = $v['width']*$v['scale'];
                $ws = $width/$arr['width'];
                $url .= '/image/'.self::qiniubase64url(tomedia($v['content']));
                $url .= "/gravity/NorthWest";
                $url .= "/dy/{$v['top']}";
                $url .= "/dx/{$v['left']}";
                $url .= "/ws/{$ws}";
            }
        }
        return $url;
    }

    public static function qiniubase64url ($str) {
        return strtr(base64_encode($str), '+/', '-_');
    }

    /* 下载图片到本地 */
    public static function downloadFile ($url,$ext=false) {
        $path = ROOT_PATH."public".DS."cache".DS;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        if(!$ext) {
            $ext = pathinfo($url, PATHINFO_BASENAME);
        }
        $filename = time().uniqid().$ext;
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
        return $path . $filename;
    }
}